package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.pojo.PlanSafeguard;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.google.common.collect.Lists;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import lombok.extern.slf4j.Slf4j;
/**
 * @Description：保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {


    @Autowired
    private PlanSafeguardServiceImpl planSafeguardService;

    @Autowired
    private CategorySafeguardServiceImpl categorySafeguardService;
    @Override
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        //1.构建分页对象
        Page<Safeguard> safeguardPage = new Page<>(pageNum, pageSize);
        //2.构建查询条件,并查询
        Page<Safeguard> page = this.lambdaQuery()
                .eq(!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKey()), Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .likeRight(!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKeyName()), Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName())
                .eq(!EmptyUtil.isNullOrEmpty(safeguardVO.getDataState()), Safeguard::getDataState, safeguardVO.getDataState())
                .page(safeguardPage);
        //3.获取查询结果
        List<Safeguard> safeguardList = page.getRecords();
        if (ObjectUtil.isEmpty(safeguardList)){
            return new Page<>();
        }
        //4.封装结果返回
        return BeanConv.toPage(page,SafeguardVO.class);
    }

    @Override
    public SafeguardVO findById(String safeguardId) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public SafeguardVO save(SafeguardVO safeguardVO) {
        //1.判断保障项的key是否为空（保障项的key是唯一的）
        Integer count = this.lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        if (count>0){
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
        //2.新增
        boolean saveResult = this.save(BeanConv.toBean(safeguardVO, Safeguard.class));
        if (!saveResult){
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
        return safeguardVO;
    }

    @Override
    @Transactional
    public Boolean update(SafeguardVO safeguardVO) {
        //修改之前要先判断关联的冗余字段
        Safeguard old = getById(safeguardVO.getId());
        if(old==null){
            log.error("原保障项不存在");
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        if(!StrUtil.equals(safeguardVO.getSafeguardKey(),old.getSafeguardKey())){
            log.error("key不能改");
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }

        Integer count1 = planSafeguardService.lambdaQuery()
                .eq(PlanSafeguard::getSafeguardKey, old.getSafeguardKey())
                .eq(PlanSafeguard::getDataState,"0")
                .count();
        Integer count2 = categorySafeguardService.lambdaQuery()
                .eq(CategorySafeguard::getSafeguardKey, old.getSafeguardKey())
                .eq(CategorySafeguard::getDataState,"0")
                .count();
        if(count1>0||count2>0){
            log.error("已被方案或分类关联，无法修改：{}",safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        Safeguard safeguard = BeanConv.toBean(safeguardVO,Safeguard.class);
        safeguard.setUpdateBy(null);
        safeguard.setUpdateTime(null);
        return this.updateById(safeguard);
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //1.将数组转换为集合
        List<String> ids = Arrays.asList(checkedIds);
        if (ObjectUtil.isEmpty(ids)){
            return true;
        }
        //2.查询其所关联的数据的数量
        Integer count1 = planSafeguardService.lambdaQuery()
                .eq(PlanSafeguard::getSafeguardKey, ids)
                .count();
        Integer count = categorySafeguardService.lambdaQuery()
                .eq(CategorySafeguard::getSafeguardKey, ids)
                .count();
        //3.判断其所关联的表是否数据为0，为0可以删除，不为0不能删除
        if (count>0|| count1>0){
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
        boolean removeByIds = this.removeByIds(ids);
        return removeByIds;
    }

    @Override
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        //TODO
        return null;
    }


    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        //TODO
        return null;
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        //TODO
        return null;
    }
}
